const Router = require('koa-router')
const Product = require('../schema/Product')
const config = require('../config')
const parse = require('async-busboy')

const productRouter = new Router({
  prefix: '/nodeApi/product'
})

productRouter.get('/findByPage', async ctx => {
  let query = {
    status: 'published'
  }
  let offset = ctx.query.offset;
  let brand = ctx.query.brand;
  if (offset && brand) {
    query.brand = brand;
    let searchText = ctx.query.searchText;
    if (searchText) {
      let searchReg = new RegExp(searchText, 'i')
      query.$or = [
        {
          title: { $regex: searchReg }
        },
        {
          sku: { $regex: searchReg }
        }
      ]
    }
    let products = await Product.paginate(query, { offset: offset, limit: 20 })
    ctx.body = products
  } else {
    ctx.body = {
      result: 'fail'
    }
  }
})

productRouter.get('/admin/findByPage', async ctx => {
  let query = {};
  let brand = ctx.query.brand;
  let status = ctx.query.status;
  let sku = ctx.query.sku;
  let title = ctx.query.title;
  let page = ctx.query.page;
  let limit = ctx.query.limit;
  let sort = '-generateTime';
  if (page && limit) {
    if (brand) {
      query.brand = brand;
    }
    if (status) {
      query.status = status;
    }
    if (sku) {
      query.sku = {
        $regex: new RegExp(sku, 'i')
      }
    }
    if (title) {
      query.title = {
        $regex: new RegExp(title, 'i')
      }
    }
    if (ctx.query.sort) {
      sort = ctx.query.sort
    }
    let products = await Product.paginate(query, { page, limit, sort });
    ctx.body = products;
  } else {
    ctx.status = 400;
    ctx.body = {
      result: 'fail'
    }
  }
})

productRouter.delete('/admin/remove', async ctx => {
  let sku = ctx.request.body
  if (sku) {
    await Product.deleteMany({ sku })
    ctx.body = {
      result: 'success'
    }
  } else {
    ctx.status = 400;
    ctx.body = {
      result: 'fail'
    }
  }
})

productRouter.patch('/admin/update/:sku', async ctx => {
  let sku = ctx.params.sku
  let body = ctx.request.body
  // await Product.updateOne({ sku }, { $set: ctx.request.body })
  let product = await Product.findOne({ sku })
  delete body.__v
  product.set(body)
  await product.save()
  ctx.body = {
    result: 'success'
  }
})

productRouter.post('/admin/new', async ctx => {
  let product = ctx.request.body
  await new Product(product).save()
  ctx.body = {
    result: 'success'
  }
})

productRouter.patch('/admin/media/:sku', async ctx => {
  let sku = ctx.params.sku
  await Product.updateOne({ sku }, { $set: ctx.request.body })
  ctx.body = {
    result: 'success'
  }
})

productRouter.post('/admin/oss', async ctx => {
  const { fields, files } = await parse(ctx.req);
  try {
    if (!fields.sku || fields.length == 0) {
      throw new Error('400-Bad request')
    } else {
      let client = config.oos;
      let fileName = fields.sku + '/' + Date.now();
      let type = '';
      if (files[0].mimeType.startsWith('image')) {
        type = 'img'
        if (files[0].mimeType.endsWith('jpeg')) {
          fileName += '.jpg'
        } else if (files[0].mimeType == 'image/gif') {
          fileName += '.gif'
        } else if (files[0].mimeType == 'image/png') {
          fileName += '.png'
        } else {
          throw new Error('400-图片格式不支持')
        }
      } else if (files[0].mimeType.startsWith('video')) {
        type = 'video'
        if (files[0].mimeType.endsWith('mp4')) {
          fileName += '.mp4'
        }
      } else {
        throw new Error('400-文件格式不支持')
      }
      let result = await client.put(fileName, files[0]);
      // "https://ruixue-test.oss-cn-shanghai.aliyuncs.com/test.jpg?x-oss-process=image/format,webp"
      // console.log(result)
      ctx.body = {
        result: 'success',
        url: result.url,
        type: type
      }
    }
  } catch (error) {
    if (error.message.startsWith('400')) {
      ctx.status = 400;
      ctx.body = {
        msg: error.message
      }
    } else {
      ctx.status = 500;
      ctx.body = {
        msg: error.message
      }
    }
  }
})

module.exports = productRouter